#include "stdafx.h"
#include "ComReader.h"

CComReader CComReader::m_sInstance;

CComReader::CComReader(void)
{
	m_hPort = INVALID_HANDLE_VALUE;
}


CComReader::~CComReader(void)
{
}

CComReader& CComReader::GetInstance(void)
{
	return m_sInstance;
}

BOOL CComReader::Start(const char* szPortName, UINT32 dwBaudRate)
{
	INT32 nRetCode = 0;

	m_hPort = ::CreateFile(szPortName, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if(m_hPort == INVALID_HANDLE_VALUE)
		return FALSE;

	DCB dcb;
	GetCommState(m_hPort, &dcb);

	dcb.BaudRate = dwBaudRate;
	dcb.ByteSize = 8;
	dcb.fBinary = TRUE;

	nRetCode = SetCommState(m_hPort, &dcb);
	if(!nRetCode)
		return FALSE;

	nRetCode = m_Buffer.Init(1024);
	if(!nRetCode)
		return FALSE;

	nRetCode = m_PacketBuffer.Init(1024);
	if(!nRetCode)
		return FALSE;

	nRetCode = _Begin();
	if(!nRetCode)
		return FALSE;

	return TRUE;
}

BOOL CComReader::Read(EulerAngle* Angle)
{
	INT32 nRetCode = 0;

	return m_PacketBuffer.Read((char*)Angle, sizeof(EulerAngle));
}

BOOL CComReader::Update(void)
{
	INT32 nRetCode = 0;
	INT32 nBytes = 0;

	if(m_hPort == INVALID_HANDLE_VALUE)
		return FALSE;

	DWORD dwRead = 0;

	char pReadBuf[512] = { 0 };

	nRetCode = ::ReadFile(m_hPort, pReadBuf, sizeof(pReadBuf), &dwRead, NULL);
	if(!nRetCode)
		return FALSE;

	char* p = strstr(pReadBuf, "#");
	if(p == NULL)
		return TRUE;

	nRetCode = m_Buffer.Write(p + 1, dwRead - (p-pReadBuf+1));

	while(true)
	{
		char pBuf[64] = { 0 };
		EulerAngle Angle;

		nBytes = m_Buffer.PreRead('#');
		if(!nBytes)
			break;

		nRetCode = m_Buffer.Read(pBuf, nBytes);
		if(!nRetCode)
			break;

		char roll[64] = { 0 };
		char pitch[64] = { 0 };

		char* delim = strstr(pBuf, ",");
		if(delim == NULL)
			continue;

		strncpy(roll, pBuf, delim - pBuf);

		char* end = strstr(delim, "#");
		if(end == NULL)
			continue;

		strncpy(pitch, delim + 1, end - delim - 1);

		Angle.roll = atof(roll);
		Angle.pitch = atof(pitch);

		nRetCode = m_PacketBuffer.Write((char*)&Angle, sizeof(Angle));
		if(!nRetCode)
			break;
	}

	return TRUE;
}

void CComReader::OnTerminate(void)
{
	CloseHandle(m_hPort);

}
